from django.shortcuts import render
from django.conf import settings
from .models import *
from .serializers import *
from workflow.models import *
from workflow.serializers import *
from users.serializers import *
from utils.token_utils import check_token

from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status

from django.db.models import Q
from django.db.models import F

import string
import random
import json
import os
import jwt


# 审批类型
class VettingViews(ViewSet):

    def add_vetting(self, request):
        try:
            name = request.data.get("name")
            lastervisename = request.data.get("lastrevisename")
            lastrevisetime = request.data.get("lastrevisetime")
            template = request.data.get("template")
            print(request.data)

            if TypeModel.objects.filter(is_delete=0, name=name).count() != 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg":'该类别已存在'})

            templates = Template.objects.filter(is_delete=0)
            template_ser = TemplateSer(templates,many=True).data
            for template_name in template_ser:
                if template_name.get("template_name") == template:
                    template = template_name.get("id")

            users = UserModel.objects.filter(is_delete=0)
            users_ser = UserSer(users,many=True).data
            for users_name in users_ser:
                if users_name.get("name") == lastervisename:
                    lastervisename = users_name.get("id")
            data = {
                "name": name,
                "lastervisename": lastervisename,
                "upd_time": lastrevisetime,
                "template_id": template
            }

            ser = TypeSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})

            TypeModel.objects.create(name=name, template_id=template, upd_time=lastrevisetime, lastervisename_id=lastervisename)
            return Response({"code": status.HTTP_200_OK, "msg":"添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def all_vetting(self, request):
        try:
            type = TypeModel.objects.filter(is_delete=0)
            type_ser = TypeSer(type, many=True)
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data": type_ser.data})
        except Expense as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 审批类型2
class VettingViewsTow(ViewSet):

    def one_vetting(self, request, pk):
        try:
            type = TypeModel.objects.filter(is_delete=0, id=pk)
            type_ser = TypeSer(type,many=True)
            return Response({"code": status.HTTP_200_OK,"msg": "获取成功","data": type_ser.data})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})

    def upd_vetting(self, request, pk):
        try:
            name = request.data.get("name")
            lastervisename = request.data.get("lastrevisename")
            lastrevisetime = request.data.get("lastrevisetime")
            template = request.data.get("template")
            print(request.data)


            templates = Template.objects.filter(is_delete=0)
            template_ser = TemplateSer(templates,many=True).data
            for template_name in template_ser:
                if template_name.get("template_name") == template:
                    template = template_name.get("id")

            users = UserModel.objects.filter(is_delete=0)
            users_ser = UserSer(users,many=True).data
            for users_name in users_ser:
                if users_name.get("name") == lastervisename:
                    lastervisename = users_name.get("id")

            data = {
                "name": name,
                "lastervisename": lastervisename,
                "upd_time": lastrevisetime,
                "template_id": template
            }

            ser = TypeSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})

            TypeModel.objects.filter(id=pk).update(name=name,template_id=template,upd_time=lastrevisetime,lastervisename_id=lastervisename)
            return Response({"code": status.HTTP_200_OK,"msg": "修改成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})

    def del_vetting(self, request, pk):
        try:
            TypeModel.objects.filter(id=pk).update(is_delete=1)
            return Response({"code": status.HTTP_200_OK,"msg": '删除成功'})
        except Exception as e:
            print("删除",e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 审批流程
class ApprovalsViews(ViewSet):

    def all_approvals(self, request):
        try:
            flow = FlowModel.objects.filter(is_delete=0)
            flow_ser = FlowSer(flow, many=True)
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data": flow_ser.data})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def add_approvals(self, request):
        try:
            name = request.data.get("name")
            state = request.data.get("state")
            lastrevisename = request.data.get("lastrevisename")
            lastrevisetime = request.data.get("lastrevisetime")
            levels = request.data.get("levels")
            peocess = request.data.get("peocess")
            print(request.data)
            print(levels)

            users = UserModel.objects.filter(is_delete=0)
            users_ser = UserSer(users,many=True).data
            for users_name in users_ser:
                if users_name.get("name") == lastrevisename:
                    lastrevisename = users_name.get("id")
                    position_id = users_name.get("position")
            print("职位id",position_id)
            position = PositionModel.objects.get(id=position_id)
            position_ser = PositionSer(position).data
            print(position_ser)
            data = {
                "flow_name": name,
                "currentvetting": lastrevisename,
                "is_enable": 1,
                "level": levels,
                "start_time":lastrevisetime,
                "peocess":peocess,
                "department": position_ser.get("department")
            }

            ser = FlowSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            flow = FlowModel.objects.create(flow_name=name, currentvetting_id=lastrevisename, level_id=levels, department_id=position_ser.get("department"),peocess=peocess)
            # flow_ser = FlowSer(flow).data
            # flow_ser_id = flow_ser.get("id")
            # UserFlowNodeModel.objects.create(name_id=lastrevisename, flow_node_id=flow_ser_id)
            return Response({"code": status.HTTP_200_OK, "msg":"添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 审批流程tow
class ApprovalsViewsTow(ViewSet):

    def one_approvals(self, request, pk):
        try:
            flow = FlowModel.objects.filter(is_delete=0, id=pk)
            flow_ser = FlowSer(flow,many=True)
            return Response({"code": status.HTTP_200_OK,"msg": "获取成功","data": flow_ser.data})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})

    def upd_approvals(self, request, pk):
        try:
            name = request.data.get("name")
            state = request.data.get("state")
            lastrevisename = request.data.get("lastrevisename")
            lastrevisetime = request.data.get("lastrevisetime")
            levels = request.data.get("levels")
            peocess = request.data.get("peocess")
            print(request.data)
            print(levels)

            if FlowModel.objects.filter(id=pk).count() == 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg":"此id不存在"})

            users = UserModel.objects.filter(is_delete=0)
            users_ser = UserSer(users,many=True).data
            for users_name in users_ser:
                if users_name.get("name") == lastrevisename:
                    lastrevisename = users_name.get("id")
                    position_id = users_name.get("position")
            print("职位id",position_id)
            position = PositionModel.objects.get(id=position_id)
            position_ser = PositionSer(position).data
            print(position_ser)

            data = {
                "flow_name": name,
                "currentvetting": lastrevisename,
                "is_enable": 1,
                "level": levels,
                "start_time": lastrevisetime,
                "peocess": peocess,
                "department": position_ser.get("department")
            }

            ser = FlowSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            FlowModel.objects.filter(id=pk).update(flow_name=name,currentvetting_id=lastrevisename,level_id=levels,
                                     department_id=position_ser.get("department"),peocess=peocess)
            return Response({"code": status.HTTP_200_OK,"msg": "修改成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})

    def del_approvals(self, request, pk):
        try:
            FlowModel.objects.filter(id=pk).update(is_delete=1)
            return Response({"code": status.HTTP_200_OK,"msg": '删除成功'})
        except Exception as e:
            print("删除",e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 我发起的流程
class InitiationsViews(ViewSet):

    def add_initiations(self, request):
        try:
            # 接受前端数据
            name = request.data.get("name")
            approvaltype = request.data.get("approvaltype")
            applicationtime = request.data.get("applicationtime")
            # approver = request.data.get("approver")
            # approvaltatus = request.data.get("approvaltatus")
            sector = request.data.get("sector")
            # flow = request.data.get("flow")
            print(request.data)

            # 获取用户所对应信息
            users = UserModel.objects.filter(is_delete=0)
            users_ser = UserSer(users,many=True).data
            # 将用户名变为其所对应的id
            for users_name in users_ser:
                if users_name.get("name") == name:
                    name = users_name.get("id")
            print("修改后",name)

            # 获取所有类别信息
            types = TypeModel.objects.filter(is_delete=0)
            types_ser = TypeSer(types,many=True).data

            # 循环类别信息
            for type_name in types_ser:
                # 判断类别名是否跟接收的想等
                if type_name.get("name") == approvaltype:
                    # 相等了变成所对应的id
                    approvaltype = type_name.get("id")
                    # 获取类别中所对应的部门信息
                    template = type_name.get("template_id")
                    template = Template.objects.get(id=template)
                    templates_ser = TemplateSer(template).data
                    # 根据部门的id查询与其所对应的流程信息， 得到所对应的流程id
                    flow = FlowModel.objects.get(id=templates_ser["id"])
                    flow_ser = FlowSer(flow).data
                    flow_id = flow_ser["id"]
            print("flow_id",flow_id)
            print("修改后类别", approvaltype)

            # 获取部门信息， 并得到与接受的名字相等的信息的id
            departments = DepartmentModel.objects.filter(is_delete=0)
            departments_ser = DepartmentSer(departments,many=True).data
            for department_name in departments_ser:
                if department_name.get("name") == sector:
                    sector = department_name.get("id")

            print("修改后sector", sector)
            # 生成参数用于校验
            data = {
                "flow": flow_id,
                "vettypes": approvaltype,
                "user_name": name,
                "vettime": applicationtime,
                "level": "2"
            }
            ser = FlowNodeSer(data=data)
            print("data后")
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            print("校验后")
            # 根据生成的参数添加数据
            FlowNodeModel.objects.create(flow_id= flow_id,vettypes_id= approvaltype,vettsatus= 0,user_name_id=name,vettime= applicationtime,level_id= 2)

            return Response({"code": status.HTTP_200_OK, "msg":"添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def get_initiations(self, request):
        try:
            # 获取前端数据token
            token2 = request.META.get("HTTP_AUTHORIZATION")
            print("token2>>>>>>>>>>>>>>>>>>>>>>>>>", token2)
            payload = check_token(token2)
            # print("payload>>>>>>>>>>>>>>>>>",payload)
            # print(payload.get("id"))
            # request.session["id"] = payload.get("id")
            # print("setting", request.session.get("id"))
            id = payload.get("id")
            print("id>>>>>>>>>>>>>>", id)
            # id = request.session.get("id")
            # 获取流程表里面跟用户名所对应的数据
            flow_node = FlowNodeModel.objects.filter(user_name=id)
            flow_node_ser = FlowNodeSer(flow_node, many=True).data
            print("for",flow_node_ser)

            # 获取用户表里面跟用户所对应的数据
            user = UserModel.objects.filter(id=id)
            user_ser = UserSer(user, many=True)
            # print("用户信息",user_ser.data)
            # 循环流程数据
            for flow_node in flow_node_ser:
                # 循环用户数据
                for user in user_ser.data:
                    # 获取到职位的id并查询
                    position_id = user.get("position")
                    print("position_id",position_id)
                    position = PositionModel.objects.filter(id=position_id)
                    position_ser = PositionSer(position,many=True)
                    # 循环职位信息
                    for position in position_ser.data:
                        # print("职位信息",position)
                        # 合成信息
                        # 根据职位信息获取到部门信息并交给流程（序列化器反向查询了）
                        flow_node["department"] = position.get("departmentname")
                # 判断审批信息并改正
                if int(flow_node.get("vettsatus")) == 0:
                    flow_node["vettsatus"] = "未审批"

                elif int(flow_node.get("vettsatus")) == 1:
                    flow_node["vettsatus"] = "同意"

                elif int(flow_node.get("vettsatus")) == 2:
                    flow_node["vettsatus"] = "驳回"

            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data": flow_node_ser})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 我发起的流程2
class DetailsViews(ViewSet):

    def one_details(self, request, pk):
        try:
            # 获取单个流程信息
            flow_node = FlowNodeModel.objects.get(id=pk)
            flow_node_ser = FlowNodeSer(flow_node).data
            print(flow_node_ser)

            # 获取与流程关联用户的信息
            user = UserModel.objects.filter(id=flow_node_ser.get("user_name"))
            user_ser = UserSer(user, many=True)
            print("用户信息",user_ser.data)

            # 便利
            for user in user_ser.data:
                # 用户的职位信息（id）
                position_id = user.get("position")
                print("position_id",position_id)

                # 根据职位的id查询出部门信息
                position = PositionModel.objects.filter(id=position_id)
                position_ser = PositionSer(position,many=True)
                print("serserwe",flow_node_ser)
                for position in position_ser.data:
                    # print("职位信息",position)
                    # 合成信息
                    # 给流程添加部门名称（返回数据）
                    flow_node_ser["department"] = position.get("departmentname")
            # 将整形状态修改为所对应的数据
            if int(flow_node_ser.get("vettsatus")) == 0:
                flow_node_ser["vettsatus"] = "未审批"

            elif int(flow_node_ser.get("vettsatus")) == 1:
                flow_node_ser["vettsatus"] = "同意"

            elif int(flow_node_ser.get("vettsatus")) == 2:
                flow_node_ser["vettsatus"] = "驳回"

            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data": flow_node_ser})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def del_details(self, request, pk):
        try:
            FlowNodeModel.objects.filter(id=pk).delete()
            return Response({"code": status.HTTP_200_OK,"msg": '撤销成功'})
        except Exception as e:
            print("删除",e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 代办事项
class TodosVews(ViewSet):

    def all_todos(self, request):
        try:
            # 获取所有代办信息（流程节点）
            flow_node = FlowNodeModel.objects.filter(vettsatus=0)
            flow_node_ser = FlowNodeSer(flow_node, many=True).data
            print(flow_node_ser)

            # 获取所有与节点信息所对应的用户id，并查询
            for flow_node in flow_node_ser:
                user = UserModel.objects.filter(id=flow_node.get("id"))
                user_ser = UserSer(user, many=True)
            # print("用户信息",user_ser.data)
                # 循环遍历用户信息
                for user in user_ser.data:
                    # 获取用户所对应的职位信息
                    position_id = user.get("position")
                    print("position_id",position_id)
                    # 根据职位查询出部门
                    position = PositionModel.objects.filter(id=position_id)
                    position_ser = PositionSer(position,many=True)
                    for position in position_ser.data:
                        # print("职位信息",position)
                        # 合成信息
                        flow_node["department"] = position.get("departmentname")
                # 修改状态
                if int(flow_node.get("vettsatus")) == 0:
                    flow_node["vettsatus"] = "未审批"

                elif int(flow_node.get("vettsatus")) == 1:
                    flow_node["vettsatus"] = "同意"

                elif int(flow_node.get("vettsatus")) == 2:
                    flow_node["vettsatus"] = "驳回"

            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data": flow_node_ser})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 已办事项
class DonesViews(ViewSet):

    def all_dones(self, request):
        try:
            # 同意已办事项
            flow_node = FlowNodeModel.objects.filter(Q(vettsatus=1)|Q(vettsatus=2))
            flow_node_ser = FlowNodeSer(flow_node, many=True).data
            print(flow_node_ser)
            for flow_node in flow_node_ser:
                user = UserModel.objects.filter(id=flow_node.get("id"))
                user_ser = UserSer(user, many=True)
            # print("用户信息",user_ser.data)
                for user in user_ser.data:
                    position_id = user.get("position")
                    print("position_id",position_id)
                    position = PositionModel.objects.filter(id=position_id)
                    position_ser = PositionSer(position,many=True)
                    for position in position_ser.data:
                        # print("职位信息",position)
                        # 合成信息
                        flow_node["department"] = position.get("departmentname")
                if int(flow_node.get("vettsatus")) == 0:
                    flow_node["vettsatus"] = "未审批"

                elif int(flow_node.get("vettsatus")) == 1:
                    flow_node["vettsatus"] = "同意"

                elif int(flow_node.get("vettsatus")) == 2:
                    flow_node["vettsatus"] = "驳回"

            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data": flow_node_ser})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 通过
class ThroughViews(APIView):

    def post(self, request, pk):
        try:
            flow = FlowNodeModel.objects.filter(id=pk).update(vettsatus=1)
            flow_ser = FlowSer(flow, many=True).data
            HistoryExaminationModel.objects.create(flow_node_id=flow_ser.get("id"))
            return Response({"code": status.HTTP_200_OK,"msg": '通过成功'})
        except Exception as e:
            print("通过",e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 驳回
class DisallowedViews(APIView):

    def post(self, request, pk):
        try:
            flow = FlowNodeModel.objects.filter(id=pk).update(vettsatus=2)
            flow_ser = FlowSer(flow,many=True).data
            HistoryExaminationModel.objects.create(flow_node_id=flow_ser.get("id"))
            return Response({"code": status.HTTP_200_OK,"msg": '驳回成功'})
        except Exception as e:
            print("驳回",e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})





















